import { SETUP_ROUTES_APIS } from '$lib/config/variable';

const generateGlobalRoutesAndApis = (handles) => {
  let routes = [];
  let apis = [];
  let newHandles = [...handles];
  const everyone = SETUP_ROUTES_APIS?.everyone;
  if (everyone?.length > 0) {
    everyone.forEach(item => {
      newHandles.unshift(item.handle);
      routes = routes.concat(item.routes);
      apis = apis.concat(item.apis);
    })
  };
  if (handles?.length > 0) {
    handles.forEach(handle => {
      if (SETUP_ROUTES_APIS?.reset?.some(r => r.handle === handle)) {
        routes = routes.concat(SETUP_ROUTES_APIS.reset.find(r => r.handle === handle).routes);
        apis = apis.concat(SETUP_ROUTES_APIS.reset.find(r => r.handle === handle).apis);
      } else {
        routes.push(`/admin/${handle}`);
        apis.push(`/api/${handle}`);
      };
    })
  };
  return { routes, apis, handles: newHandles };
}

const generateCurrentUserRoutesAndApis = (handles) => {
  let routes = [];
  let apis = [];
  let newHandles = [...handles];
  const everyone = SETUP_ROUTES_APIS?.everyone;
  if (everyone?.length > 0) {
    everyone.forEach(item => {
      newHandles.unshift(item.handle);
      routes = routes.concat(item.routes);
      apis = apis.concat(item.apis);
    })
  };
  if (handles?.length > 0) {
    handles.forEach(handle => {
      if (SETUP_ROUTES_APIS?.reset?.some(r => r.handle === handle)) {
        routes = routes.concat(SETUP_ROUTES_APIS.reset.find(r => r.handle === handle).routes);
        apis = apis.concat(SETUP_ROUTES_APIS.reset.find(r => r.handle === handle).apis);
      } else {
        routes.push(`/admin/${handle}`);
        apis.push(`/api/${handle}`);
      };
    })
  };
  return { routes, apis, handles: newHandles };
}

export { generateGlobalRoutesAndApis, generateCurrentUserRoutesAndApis };